import re

from django import forms

from App.bootstrap import BootStrapModelForm
from App.models import User
from App.utils.my_tools import judge_password


class AddInfoForm(BootStrapModelForm):
    password = forms.CharField(
        min_length=8,
        label='密码',
        # widget=forms.PasswordInput()
    )
    headImg = forms.ImageField(
        label='用户头像',
        required=False,
    )
    name = forms.CharField(
        max_length=20,
        label='昵称',
        widget=forms.TextInput(attrs={
            'placeholder': '请输入昵称',
        })
    )
    phone = forms.CharField(
        min_length=11,
        max_length=11,
        label='电话号码',
        widget=forms.TextInput(attrs={
            'placeholder': '请输入电话号码',
        })
    )
    position = forms.ChoiceField(
        choices=(
            ("总经理", "总经理"),
            ("销售", "销售"),
            ("统筹", "统筹"),
            ("管家", "管家"),
            ("财务", "财务"),
        ),
    )

    class Meta:
        model = User  # 必须为数据库中的某个class
        fields = ['password','name', 'headImg', 'phone', 'position']  # 获取数据库中所有字段

    # 对密码进行错误判定
    def clean_password(self):
        password = self.cleaned_data.get('password')
        if judge_password(password):
            return password
        else:
            raise forms.ValidationError('密码格式错误，应由字母、数字和符号组成')

    # 判断昵称
    def clean_name(self):
        name = self.cleaned_data.get('name')
        return name

    # 判断图片格式
    def clean_headImg(self):
        if self.cleaned_data.get('headImg') != None:
            file_object = self.cleaned_data.get('headImg').name
            if file_object.split('.')[-1] not in ['jpeg', 'jpg', 'png']:
                raise forms.ValidationError('文件格式错误')

    # 判断手机号码格式
    def clean_phone(self):
        phone = self.cleaned_data.get('phone')
        ret = re.match(r"^1[35678]\d{9}", phone)
        if not ret:
            raise forms.ValidationError('手机号码格式错误')
        else:
            return phone

    # 判断职位
    def clean_position(self):
        position = self.cleaned_data.get('position')
        return position
